/*
* LayerBox浮层效果
* @author 陈桥
* @version 1.0
*/
WOYO.add('widget.LayerBox', function (W) {
    var defaultConfig = {
        struc: null, //结构弹出、结构元素
        Temps: '', //模板弹出、模板
        Data: '', //默认模板数据
        close: '.close', //close:关闭按钮默认.close
        text: 'alert 弹出浮层', //弹出层默认文本
        drag: false, //拖动效果
        dragLoc: false, //是否开启定位操作
        dragTags: '', //拖动标签
        dragBody: '', //拖动结构
        diagCursor: 'move',//拖动鼠标样式
        time: 'max', //定时器默认为不开启定时器
        isFrame: true, //是否开启遮罩层
        opacity: 0.5, //遮罩层默认透明度
        backcolor: '#ccc', //遮罩层默认背景色
        zIndex: 9, //浮层起始层级
		ParIframe: false,//开启iframe 穿透
		ParIframeMan: window.top, //默认穿透度 window.top是最顶级父窗口、window.parent是父窗口，
		isloc:false,//是否每次弹出重新定位浮层
        callback: function () { } //默认回调方法、在弹出层显示前执行
    },
    //遮罩层默认样式
	defaultMaskConfig = {
	    display: 'none',
	    position: 'absolute',
	    backgroundColor: '#ccc', //遮罩层背景色
	    zIndex: 9, //遮罩层层级
	    top: '0px',
	    left: '0px',
	    height: '768px',
	    width: '1024px',
	    backgroundImage: 'url(about:blank;)', //IE兼容设置
	    opacity: 0.5, //透明度设置
	    filter: 'alpha(opacity=50)',
	    mozOpacity: 0.5
	};
    //setOption(el, {id: 'asins', class:'bb'})
    function setOption(el, obj) {
        W.each(obj, function (val, key) {
            el[key] = val;
        });
    };

    function ClassObj(eventType, config) {
        var self = this;
        if (!(self instanceof ClassObj)) {
            return new ClassObj(eventType, W.merge(defaultConfig, config));
        }
        var config = self.config = config;
        //初始值
        //检查是否为IE6
        var ie = !((window.ActiveXObject && !window.XMLHttpRequest) == undefined ? true : false);

		//兼容穿透Iframe
        var doc = !config.ParIframe ? document : config.ParIframeMan.document;
		var win = !config.ParIframe ? window : config.ParIframeMan;

        //生成唯一标识
        var uuid = Date.parse(new Date()) + Math.floor(Math.random() * 100000);
		
		//游览器版本
		var browser = {
			"ie" : function (){
				return !!window.ActiveXObject;
			},
			"version" : function(){
				if(!-[1,]){
					var isIE=!!window.ActiveXObject; 
					var isIE6=isIE&&!window.XMLHttpRequest; 
					var isIE8=isIE&&!!document.documentMode; 
					var isIE7=isIE&&!isIE6&&!isIE8; 
					if (isIE){ 
						if (isIE6){ 
						return '6.0'; 
						}else if (isIE8){ 
						return '8.0'; 
						}else if (isIE7){ 
						return '7.0'; 
						}
					}
				}}
			}

		//outerHTML
		if(!browser.ie()){
			var pro = window.HTMLElement.prototype;
			pro.__defineGetter__("outerHTML", function(){
				var str = "<" + this.tagName;
				var a = this.attributes;
				for(var i = 0, len = a.length; i < len; i++){
					if(a[i].specified){
						str += " " + a[i].name + '="' + a[i].value + '"';  
					}
				}
			if(!this.canHaveChildren){  
				return str + " />";
			}
				return str + ">" + this.innerHTML + "</" + this.tagName + ">";
			});
			pro.__defineSetter__("outerHTML", function(s){
				var r = this.ownerDocument.createRange();
				r.setStartBefore(this);
				var df = r.createContextualFragment(s);
				this.parentNode.replaceChild(df, this);
			 return s;
			});
			pro.__defineGetter__("canHaveChildren", function(){  
				return !/^(area|base|basefont|col|frame|hr|img|br|input|isindex|link|meta|param)$/.test(this.tagName.toLowerCase());  
			});
		}

        //获取document对象
        var getDOM = function (i,dom) {
			var g_doc = dom == undefined ? doc : dom;
            this.i = i;
            switch (i.substr(0, 1)) {
                case '#': return getID(); break;
                case '.': return getClass(); break;
                default: return getClass(); break;
            }
            function getID() {
                var _tag = this.i.split('#').length > 1 ? this.i.split('#') : [null, this.i];
                return g_doc.getElementById(_tag[1]);
            }
            function getClass() {
                var _tag = this.i.split('.').length > 1 ? this.i.split('.') : [null, this.i];
                var ele = [], all = g_doc.getElementsByTagName(_tag[0] || "*");
                for (var i = 0; i < all.length; i++) {
                    if (all[i].className.split(' ').length == 1) {
                        all[i].className == _tag[1] && ele.push(all[i]);
                    } else {
                        var lablespt = all[i].className.split(' ');
                        for (var slt = 0; slt < lablespt.length; slt++) {
                            lablespt[slt] == _tag[1] && ele.push(all[i]);
                        }
                    }
                }
                return ele;
            }
        };
		//事件绑定
        var eventUtil = {
            "addEvent": doc.addEventListener ?
			function (el, type, fn, capture) {
			    if (el.addEventListener) {
			        el.addEventListener(type, fn, false);
			    }
			} :
			function (el, type, fn) {
			    if (el.attachEvent) {
			        el.attachEvent('on' + type, fn);
			    }
			},
            "removeEvent": doc.removeEventListener ?
			function (el, type, fn, capture) {
			    if (el.removeEventListener) {

			        el.removeEventListener(type, fn, false);
			    }
			} :
			function (el, type, fn) {
			    if (el.detachEvent) {
			        el.detachEvent('on' + type, fn);
			    }
			}
        };
        //eventUtil.addEvent(document, 'resize', function);
        //eventUtil.addEvent(window, 'resize', imgLoad);
        //点击事件
        var click = function (doc, fn) {
            if (doc.length != undefined) {
                for (var ic = 0; ic < doc.length; ic++) {
                    eventUtil.addEvent(doc[ic], 'click', function (e) {e = e || event; !browser.ie() ? e.preventDefault() : e.returnValue = false; fn() ;}); //绑定并清除默认事件
                }
            } else {
                eventUtil.addEvent(doc, 'click', function (e) {e = e || event; !browser.ie() ? e.preventDefault() : e.returnValue = false; fn() ;}); //绑定并清除默认事件
            }
        };
        //获取子节点
        function getNexts(obj, tags) {
            var labels = obj.childNodes, nextList = [], t = tags.substr(0, 1);
            getNex(labels);
            function getNex(labels) {
                for (var iLoop = 0; iLoop < labels.length; iLoop++) {
                    var label = labels[iLoop];
                    if (label.nodeType == 1) {
                        if (t == '.') {
                            //获取class
                            if (label.className.split(' ').length == 1) {
                                label.className == tags.split('.')[1] && nextList.push(label);
                            } else {
                                var lablespt = label.className.split(' ');
                                for (var slt = 0; slt < lablespt.length; slt++) {
                                    lablespt[slt] == tags.split('.')[1] && nextList.push(label);
                                }
                            }
                        } else if (t == '#') {
                            //获取id
                            label.getAttribute('id') == tags.split('#')[1] && nextList.push(label);
                        } else {
                            //获取标签
                            label.tagName.toLowerCase() == tags && nextList.push(label);
                        }
                        if (label.childNodes.length >= 1) {
                            getNex(label.childNodes);
                        }
                    }
                }
            }
            return nextList;
        };
        //获取父节点
        function getParents(obj, tags) {
            var nextList = [], t = tags == '' && tags.substr(0, 1);
            getNex(obj);
            function getNex(labels) {
                var label = labels.parentNode;
                if (label.nodeType == 1) {
                    if (t == '.') {
                        //获取class
                        if (label.className.split(' ').length == 1) {
                            label.className == tags.split('.')[1] && nextList.push(label);
                        } else {
                            var lablespt = label.className.split(' ');
                            for (var slt = 0; slt < lablespt.length; slt++) {
                                lablespt[slt] == tags.split('.')[1] && nextList.push(label);
                            }
                        }
                        //label.className == tags.split('.')[1] && nextList.push(label);//获取class
                    } else if (t == '#') {
                        label.getAttribute('id') == tags.split('#')[1] && nextList.push(label); //获取id
                    } else {
                        //nextList.push(label);//获取标签
                    }
                    if (label.tagName != 'BODY') {
                        getNex(label);
                    }
                }
            }
            return nextList;
        };

        /**
        template格式和数组格式如下
        var template = "<div><h1>{title}</h1><p>{content}</p></div>";
        var data = {title:"a",content:"aaaa"};
        只需要数据格式对应
        */
        function dataTemplate(template, data) {
            var matchs = template.match(/\{[a-zA-Z]+\}/gi);
            for (var i = 0; i < matchs.length; i++) {
                var re_match = matchs[i].replace(/[\{\}]/gi, "");
                template = template.replace(matchs[i], data[re_match]);
            }
            return template;
        }

        //遮罩初始化
        function Mask() {
            var _lay_MASK = getDOM('div.layerbox_mask' + uuid);
            if (!_lay_MASK.length) {
                //创建div 元素
                this.el = doc.body.appendChild(doc.createElement('DIV'));
                //遮罩层样式设置
                var page = {
                    backgroundColor: config.backcolor,
                    zIndex: config.zIndex,
                    height: Math.max(doc.documentElement.clientHeight, doc.documentElement.scrollHeight) + 'px',
                    width: Math.max(doc.documentElement.clientWidth, doc.documentElement.scrollWidth) + 'px',
                    opacity: config.opacity, //firefox3.5 + 
                    filter: "alpha(opacity=" + (config.opacity * 100) + ")", //IE6 + 
                    mozOpacity: config.opacity//firefox3.5 -
                };
                setOption(this.el.style, W.merge(defaultMaskConfig, page)); //设置样式
                var _thiselstyle = this.el.style;
                //游览器状态发生变化时执行

                eventUtil.addEvent(win, 'resize', function () {
                    _thiselstyle.height = Math.max(doc.documentElement.clientHeight, doc.documentElement.scrollHeight) + 'px';
                    _thiselstyle.width = Math.max(doc.documentElement.clientWidth, doc.documentElement.scrollWidth) + 'px';
                });

                //遮罩层name
                this.el.className = 'layerbox_mask' + uuid;
                //判断是否IE6.0
                if (browser.version() == 6.0) {
                    var css = 'width:100%;height:100%;display:block;filter:Alpha(opacity=0);';
                    this.el.innerHTML = '<iframe frameborder="no" style="' + css + '"></iframe><div style="position:absolute;z-index:2;left:0;top:0;' + css + '"></div>';
                };
            } else {
                this.el = _lay_MASK[0];
            }
        };
        Mask.prototype = {
            show: function (zIndex) {
                this.el.style.display = 'block';
            },
            hide: function () {
                this.el.style.display = 'none';
            }
        };
        //浮层定位
        function Location() {
            //居中定位
            this.center = function (obj) {
                obj.style.display = 'block'; //显示取值
                var _ht = obj.offsetHeight, _wt = obj.offsetWidth;
                obj.style.display = 'none';
                obj.style.top = (browser.version() != 6.0 ? (doc.documentElement.clientHeight - _ht) / 2 : (doc.documentElement.clientHeight - _ht) / 2 + doc.documentElement.scrollTop) + 'px';
                obj.style.left = (doc.documentElement.clientWidth - _wt) / 2 + 'px';
                obj.style.position = 'fixed';
                obj.style.zIndex = config.zIndex + 1;
                //游览器状态发生变化时执行
                eventUtil.addEvent(win, 'resize', function () {
                    obj.style.top = (browser.version() != 6.0 ? (doc.documentElement.clientHeight - _ht) / 2 : (doc.documentElement.clientHeight - _ht) / 2 + doc.documentElement.scrollTop) + 'px';
                    obj.style.left = (doc.documentElement.clientWidth - _wt) / 2 + 'px';
                });
                //ie6兼容
                if (browser.version() == 6.0) {
                    obj.style.position = 'absolute';
                    eventUtil.addEvent(win, 'scroll', function () {
                        obj.style.top = (doc.documentElement.clientHeight - _ht) / 2 + doc.documentElement.scrollTop + 'px';
                    });
                }
            }
        }
        function docSize(client, div_body) {//获取页面大小
            var dd = doc.documentElement, db = doc.body, M = Math.max;
            var doc_v = doc.compatMode == "CSS1Compat" ? dd : db;
            return {
                left: M(dd.scrollLeft, db.scrollLeft),
                top: M(dd.scrollTop, db.scrollTop),
                width: doc_v[(client ? 'client' : 'scroll') + 'Width'],
                height: client ? doc_v.clientHeight : M(doc_v.clientHeight, doc_v.scrollHeight)
            }
        }
        function drag(title, body) {//拖动
            var w = body, by = body || title, x, y, _left, _top, v; //属性赋值
            v = docSize(true);
            if (title.length != undefined) {
                for (var ic = 0; ic < title.length; ic++) { title[ic].onmousedown = fn; title[ic].style.cursor = config.diagCursor; }; //绑定鼠标按下事件
            } else {
                title.onmousedown = fn; title.style.cursor = config.diagCursor;
            }
            function fn(e) {
                e = e || win.event;
                x = e.clientX, y = e.clientY, _left = by.offsetLeft, _top = by.offsetTop; //获取属性
                by.ondragstart = this.ondragstart = function () { return false };
                doc.onmousemove = e_move; //绑定鼠标拖动事件
                if (title.setCapture) title.setCapture(); //拖动元素鼠标按下属性
                doc.onlosecapture = win.onblur = doc.onmouseup = undrag; //鼠标释放事件
                if (e.preventDefault) e.preventDefault()//阻止FF拖动滚动条
            };
            function e_move(e) {//鼠标拖动执行方法
                e = e || win.event;
                var cl = _left + e.clientX - x, ct = _top + e.clientY - y; //获取当前top left
                w.style.left = cl + 'px';
                w.style.top = ct + 'px';
                //w.getSelection?w.getSelection().removeAllRanges():doc.selection.empty();
            };
            function undrag(e) {//鼠标释放执行方法
                //越界校正
                var dox, doy;
                var x = by.offsetLeft, y = by.offsetTop, w = by.offsetWidth, h = by.offsetHeight;
                var right = v.left + v.width - w, bottom = v.top + v.height - h;
                if (y < 0) { t2 = 0; doy = true };
                if (x < 0) { t = 0; dox = true };
                if (x > right) { t = right; dox = true };
                if ((y + v.top) > bottom) { t2 = bottom - v.top; doy = true; };
                if (doy || dox) {
                    if (dox) { by.style.left = (t) + 'px'; }
                    if (doy) { by.style.top = (t2) + 'px'; }
                }
                win.onblur = this.onmouseup = this.onmousemove = null;
                if (title.releaseCapture) title.releaseCapture(); //拖动元素鼠标释放属性

                //window.onblur=this.onmouseup=this.onmousemove=null;
                //if(title.releaseCapture)title.releaseCapture();//拖动元素鼠标释放属性
            }
        }

        //点击弹出层
        function Dialog() {
            //初始化方法
            this.al = doc.body.appendChild(doc.createElement('DIV'));
            this.al.className = "layerbox_dialog_alert";
            //遮罩层样式设置
            var page = {
                position: 'absolute',
                width: 'auto',
                height: 'auto',
                zIndex: config.zIndex + 1,
                display: 'none',
                backgroundColor: '#FFF',
                fontSize: '12px',
                border: '2px solid #d8d8d8',
                textAlign: 'center',
                float: 'left'
            };
            setOption(this.al.style, page); //设置样式
            this.al.innerHTML = '';
        };
        Dialog.prototype = {
            show: function (text) {
                this.al.style.display = 'block';
            },
            hide: function () {
                this.al.style.display = 'none';
            }
        };
        var style = function () {
            this.dialog = null;
            this._mk = null;
            this._close = null;
        };
        //遮罩层
        style.mask = function () {
            var _mask = null;
            if (config.isFrame) {
                _mask = new Mask();
            };
            this.mask_show = function (time) {//遮罩层显示
                _mask && _mask.show();
            }
            this.mask_hide = function () {//遮罩层隐藏
                _mask && _mask.hide();
            };
        };
        //弹出层效果
        var st = new style();
        style.alert = function (text, time) {
			var loc,Tag;
            if (!st.dialog) {
                st.dialog = new Dialog(); //初始弹出层
                st._mk = new style.mask(); //初始化遮罩层
                st.dialog.al.innerHTML = '<p style="margin:20px 50px 5px 50px">' + (text || config.text) + '</p><button style="width:auto;height:auto;margin:10px 10px 10px 10px" class="close">关闭</button>'; //默认弹出层结构
                loc = new Location();
                loc.center(st.dialog.al);
				Tag =  getNexts(st.dialog.al, config.dragTags);
                config.drag && drag(Tag.length == 0 ? st.dialog.al : Tag, st.dialog.al);//是否开启拖动效果
            }
			if(config.isloc) {loc = new Location();loc.center(st.dialog.al);}
            st._mk.mask_show(); //显示遮罩
            st.dialog.show(); //显示弹出
            if (config.time != 'max' || time != undefined) { var stout = setTimeout(hide, time || config.time); } //定时隐藏弹出层
            st._close = function () {//关闭方法
                clearInterval(stout);
                hide();
            }
            click(getNexts(st.dialog.al, config.close), st._close); //关闭按钮绑定关闭事件
            function hide() {
                st._mk.mask_hide();
                st.dialog.hide();
            };
        };

        //弹出结构
        style.struc = function (time) {
			var loc,Tag;
            if (!st.dialog) {
				//st.dialog = new Dialog(); //初始弹出层
                st._mk = new style.mask(); //初始化遮罩层
				if(!config.ParIframe){
					var con_str = getDOM(config.struc); //获取节点dom
					st.dialog = con_str.length != 'undefined' ? con_str : con_str[0];
					
				}else{//添加复制穿透iframe弹出结构
					var con_str = getDOM(config.struc,document);//从本页面获取document节点
					st.dialog = doc.body.appendChild(doc.createElement('DIV'));
					st.dialog.innerHTML = (con_str.length != 'undefined' ? con_str : con_str[0]).outerHTML;//把当前层写入到父级
					var con_str = getDOM(config.struc); //从新从父页获取节点dom
					st.dialog = con_str.length != 'undefined' ? con_str : con_str[0];//重新附值给dialog
					config.callback(); //执行回调方法
				}
                loc = new Location();
                loc.center(st.dialog);
				Tag =  getNexts(st.dialog, config.dragTags);
                config.drag && drag(Tag.length == 0 ? st.dialog : Tag, st.dialog);//是否开启拖动效果
            }
			if(config.isloc) {loc = new Location();loc.center(st.dialog);}
            st._mk.mask_show(); //显示遮罩
            st.dialog.style.display = 'block'; //显示弹出
            if (config.time != 'max' || time != undefined) { var stout = setTimeout(hide, time || config.time); } //定时隐藏弹出层
            st._close = function () {//关闭方法
                clearInterval(stout); //关闭定时器
                hide();
            };
            click(getNexts(st.dialog, config.close), st._close); //关闭按钮绑定关闭事件
            function hide() {
                st._mk.mask_hide();
                st.dialog.style.display = 'none';
            };
        };

        //弹出模板
        style.Temps = function (data, time) {
			var loc,Tag;
            if (!st.dialog) {
                st.dialog = new Dialog(); //初始弹出层
                st._mk = new style.mask(); //初始化遮罩层
                st.dialog.al.innerHTML = dataTemplate(config.Temps, data || config.data); //默认弹出层结构 dataTemplate 模板替换方法
                loc = new Location();
                loc.center(st.dialog.al); //定位操作
                config.callback(); //执行回调方法
				Tag =  getNexts(st.dialog.al, config.dragTags);
                config.drag && drag(Tag.length == 0 ? st.dialog.al : Tag, st.dialog.al);//是否开启拖动效果
            }
			if(config.isloc) {loc = new Location();loc.center(st.dialog);}
            st._mk.mask_show(); //显示遮罩
            st.dialog.al.style.display = 'block'; //显示弹出
            if (config.time != 'max' || time != undefined) { var stout = setTimeout(hide, time || config.time); } //定时隐藏弹出层
            st._close = function () {//关闭方法
                clearInterval(stout);
                hide();
            };
            click(getNexts(st.dialog.al, config.close), st._close); //关闭按钮绑定关闭事件
            function hide() {
                st._mk.mask_hide();
                st.dialog.al.style.display = 'none';
            };
        };

        //层拖动效果
        style.Drag = function (Tags, Body) {
            if (!st.dialog) {
                var con_str = getDOM(config.dragBody || Body); //获取节点dom
                st.dialog = con_str.length != 'undefined' ? con_str : con_str[0];
                if (browser.version() == 6.0) { st.dialog.style.position = 'absolute'; } else { st.dialog.style.position = 'fixed'; } //添加必须样式
                if (config.dragLoc) {//是否开启默认居中定位操作
                    var _oldlay = st.dialog.style.display; //获取默认层状态
                    var loc = new Location(); //默认方法
                    loc.center(st.dialog); //居中定位
                    st.dialog.style.display = _oldlay; //恢复默认状态
                }
            }
			var Tag =  getNexts(st.dialog, config.dragTags);
            drag(Tag.length == 0 ? st.dialog : Tag, st.dialog);
			if (config.time != 'max') { var stout = setTimeout(hide, config.time); } //定时隐藏弹出层
			st._close = function () {//关闭方法
                clearInterval(stout);
                hide();
            };
            click(getNexts(st.dialog, config.close), st._close); //关闭按钮绑定关闭事件
            function hide() {
                st.dialog.style.display = 'none';
            };
        };

        //弹出定位操作
        style.position = function () {};
        //关闭方法
        style.close = function () {
            st._close();
        };
        //点击弹出层
        function mask_show(time) {
            _mask.show();
        };
        function mask_hide() {
            _mask.hide();
        };
        //控制方法
        this._main = function (obj1, obj2, obj3) {
            !eventType && [eventType = 'alert']; //添加默认alert
            eventType = eventType.toLowerCase(); //转换成小写
            switch (eventType) {
                case 'alert': style.alert(obj1, obj2); break;
                case 'struc': style.struc(obj1); break;
                case 'temps': style.Temps(obj1, obj2); break;
                case 'drag': style.Drag(obj1, obj2); config.drag = true; break;
                default: style.alert(obj1); break;
            }
        };
        //关闭方法
        this._close = function () {
            style.close();
        };
		//需要初始化执行的方法
        (function () {
            switch (eventType) {
                case 'drag': style.Drag(); break;
                default: break;
            }
        })();
    };
    W.augment(ClassObj, {
        close: function () { },
        alert: function (obj1, obj2, obj3) {
            this._main(obj1, obj2, obj3);
        },
        hide: function () {
            this.hide();
        },
        show: function (time, data) {
            //this.alert('',time,data);
        },
        close: function () {
            this._close();
        }
    });
    return ClassObj;
});